#!/usr/bin/perl -w
use strict;
use Statistics::Descriptive;
srand(0);

my $stat1 = Statistics::Descriptive::Full->new();
my $stat2 = Statistics::Descriptive::Full->new();

my @system;

my $t=100000;
(defined $ARGV[0]) && ($t=$ARGV[0]);
my $time=0;
my $D_min=600;
my $N=300;
my $D_op=4;
for (my $i=0;$i<$N;$i++) {
    my $timer=$D_min+int(rand(2*$D_min));
    $stat2->add_data($timer);
    push @system,$timer;
}

while ($time<$t) {
    my $ops=0;
    for (my $c=0; $c<$N; $c++) {
	if ( $system[$c]-$time<$D_op ) {
	    $ops++;
#	    print "$time: $c is running\n";
	    if ( $time==$system[$c] ) {
		my $timer=$D_min+int(rand(2*$D_min));
		$system[$c]=$time+$timer;
		($time+$timer < $t ) && ( $stat2->add_data($timer) );
	    }
	}
    }
#    print "$time: $ops simultaneous\n";
    $stat1->add_data($ops);
    $time++;
}

open(OUTFILE,">random-histo-300-conc.dat");
my $w=1;
my @bins=();
for (my $i=0;$i<10;$i++) {
    push @bins,($w*$i);
}    
my %f = $stat1->frequency_distribution(\@bins);
my $n = $stat1->count;
for (sort {$a <=> $b} keys %f) {
    printf OUTFILE "%4.0f %4.0f\n",$_,$f{$_};
}
close OUTFILE;

$w=600;
@bins=();
for (my $i=0;$i<10;$i++) {
    push @bins,($w*$i);
}    
%f = $stat2->frequency_distribution(\@bins);
$n = $stat2->count;
for (sort {$a <=> $b} keys %f) {
    printf "%4.0f %6.2f\n",$_,$f{$_}*100/$n;
}
